package com.we.risk.antirefund.refund;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

public class TableUserAccount {
    public static final String KFKTABLE = "fdm.hhl01_user_account";
    public static final String QUERYSQL =
            "select uid, "
                    + "system_unique_id as user_key, " +
                    "updated_at "
                    + " from "
                    + KFKTABLE
                    + " where system_unique_id is not null";

    public long uid;
    public String user_key;
    public int updated_at;

    public TableUserAccount() {}

    public TableUserAccount(long uid, String user_key, int updated_at) {
        this.uid = uid;
        this.user_key = user_key;
        this.updated_at = updated_at;
    }

    public static TableUserAccount init(long uid) {
        return new TableUserAccount(uid, "", 0);
    }

    public long getUid() {
        return uid;
    }

    public String getUser_key() {
        return user_key;
    }

    public int getUpdated_at() {
        return updated_at;
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserAccount.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAccount>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAccount.class);

        SingleOutputStreamOperator<String> out = inputStream.filter(new FilterFunction<Tuple2<Boolean, TableUserAccount>>() {
            @Override
            public boolean filter(Tuple2<Boolean, TableUserAccount> value) throws Exception {
                return value.f0;
            }
        }).uid("TableUserAccount-filter")
                .keyBy(new KeySelector<Tuple2<Boolean, TableUserAccount>, Long>() {
                    @Override
                    public Long getKey(Tuple2<Boolean, TableUserAccount> value) throws Exception {
                        return value.f1.getUid();
                    }
                }).flatMap(new RichFlatMapFunction<Tuple2<Boolean, TableUserAccount>, String>() {
                    ValueState<TableUserAccount> userAccountVState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        userAccountVState = getRuntimeContext()
                                .getState(new ValueStateDescriptor<TableUserAccount>("userAccountVState", TableUserAccount.class));
                    }

                    @Override
                    public void flatMap(Tuple2<Boolean, TableUserAccount> value, Collector<String> out) throws Exception {
                        long uid = value.f1.getUid();
                        String user_key = value.f1.getUser_key();
                        int updated_at = value.f1.getUpdated_at();

                        TableUserAccount tmpState = userAccountVState.value();
                        TableUserAccount curState = (tmpState == null ? TableUserAccount.init(uid) : tmpState);

                        if (updated_at > curState.getUpdated_at()) {
                            curState.user_key = user_key;
                            JSONObject outJson = new JSONObject();
                            outJson.put("uid", uid);
                            outJson.put("user_key", user_key);
                            out.collect(outJson.toString());

                            userAccountVState.update(curState);
                        }

                    }
                });
        return out;
    }
}
